package com.vanke.kotlin

import android.graphics.drawable.Drawable
import android.support.v7.graphics.drawable.DrawerArrowDrawable
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.Toolbar
import android.view.View
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast

/**
 * @name Kotlin
 * @package name：com.vanke.kotlin
 * @class describe
 * @anthor shiyuchuan
 * @time 2017/8/1 11:47
 */
interface ToolbarManager{
    val toolbar: Toolbar

    var toolbarTitile: String
        get() = toolbar.title.toString()
        set(value) {
            toolbar.title = value
        }

    fun initToolbar() {
        toolbar.inflateMenu(R.menu.menu_main)
        toolbar.setOnMenuItemClickListener {
            when(it.itemId){
                R.id.action_setting -> toolbar.context.startActivity<SettingActivity>()
                else -> App.instance.toast("unknown opetion")
            }
            true
        }
    }

    fun enableHomeAsUp(up: () -> Unit) {
        toolbar.navigationIcon = createUpDrawable()
        toolbar.setNavigationOnClickListener { up() }
    }

    fun createUpDrawable(): Drawable = with(DrawerArrowDrawable(toolbar.context)){
        progress = 1f
        this
    }

    fun  attachToScroll(recyclerView: RecyclerView){
        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener(){
            override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
                if (dy > 0 ) toolbar.slideExit() else toolbar.slideEnter()
            }

        })
    }
}

private fun View.slideEnter() {
    if (translationY == 0f) animate().translationY(-height.toFloat())
}

private fun View.slideExit() {
    if (translationY < 0f) animate().translationY(0f)
}
